<?php

namespace App\Models\Shop;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

use DB;

class Product extends Model
{
    //软删除
    use SoftDeletes;
    protected $dates = ['deleted_at'];

    //黑名单
    protected $guarded = ['category_id', 'file', 'imgs'];


    //商品和分类,多对多的关系
    //商品属于多个分类，分类有多个商品
    public function categories()
    {
        return $this->belongsToMany('App\Models\Shop\Category');
    }

    //商品属于品牌
    public function brand()
    {
        return $this->belongsTo('App\Models\Shop\Brand');
    }

    //商品有很多相册
    public function product_galleries()
    {
        return $this->hasMany('App\Models\Shop\ProductGallery');
    }

    //模糊查询
    static function all_products($request)
    {
        $where = function ($query) use ($request) {

            //按商品名搜索
            if ($request->has('name') and $request->name != '') {
                $search = "%" . $request->name . "%";
                $query->where('name', 'like', $search);
            }
            //按所属分类查询
            if($request->has('category_id') and $request->category_id != '-1'){
                $category_id = $request->category_id;
                $product_ids = DB::table('category_product')->where('category_id',$category_id)->pluck('product_id');
                $query->whereIn('id',$product_ids);
            }

            //按品牌查询
            if ($request->has('brand_id') and $request->brand_id != '-1') {
                $query->where('brand_id', $request->brand_id);
            }
            //按上架状态查询
            if ($request->has('is_onsale') and $request->is_onsale != '-1') {
                $query->where('is_onsale', $request->is_onsale);
            }

            if ($request->has('is_top')) {
                $query->where('is_top', 1);
            }
            if ($request->has('is_recommend')) {
                $query->where('is_recommend', 1);
            }
            if ($request->has('is_new')) {
                $query->where('is_new', 1);
            }
            if ($request->has('is_hot')) {
                $query->where('is_hot', 1);
            }

            //按时间查询
            if ($request->has('created_at') and $request->created_at != '') {
                $time = explode(" ~ ", $request->input('created_at'));
                $start = $time[0] . ' 00:00:00';
                $end = $time[1] . ' 23:59:59';
                $query->whereBetween('created_at', [$start, $end]);
            }
        };
        $products = Product::with('categories', 'brand')->where($where)->orderBy('sort_order')->paginate(config('admin.page_size'));
        return $products;
    }

}
